package com.ruanmeng.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.com.ruanmeng.demon.PerMessM;
import com.com.ruanmeng.demon.QianDaoM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.ImgDataUtil;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.view.CircleImageView;
import com.example.lenovo.weiyi.MineCollectionActivity;
import com.example.lenovo.weiyi.MyErWeiMaActivity;
import com.example.lenovo.weiyi.MyServiceActivity;
import com.example.lenovo.weiyi.PayServiceActivity;
import com.example.lenovo.weiyi.PersonalDataActivity;
import com.example.lenovo.weiyi.R;
import com.example.lenovo.weiyi.SettingActivity;
import com.example.lenovo.weiyi.XiaoFeiJiLuActivity;
import com.example.lenovo.weiyi.YiJianFanKuiActivity;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.utils.Log;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;


public class MineFragment extends Fragment {


    @BindView(R.id.iv_touxiang)
    CircleImageView ivTouxiang;
    @BindView(R.id.tv_nicehng)
    TextView tvNicehng;
    @BindView(R.id.iv_qiandao)
    ImageView ivQiandao;
    @BindView(R.id.ll_personal_date)
    LinearLayout llPersonalDate;
    @BindView(R.id.ll_goumai_fuwu)
    LinearLayout llGoumaiFuwu;
    @BindView(R.id.ll_xiaofei_jilu)
    LinearLayout llXiaofeiJilu;
    @BindView(R.id.ll_my_erweima)
    LinearLayout llMyErweima;
    @BindView(R.id.ll_tuijian_share)
    LinearLayout llTuijianShare;
    @BindView(R.id.ll_set)
    LinearLayout llSet;
    //    @BindView(R.id.mine_sr_refresh)
//    SwipeRefreshLayout mRefresh;
    @BindView(R.id.tv_view)
    View tvView;
    @BindView(R.id.tv_per_jf)//我的积分
            TextView tvPerJf;
    private Request<String> mRequest;
    private View fview;
    private Intent intent;
    private LinearLayout ll_share_qq;
    private LinearLayout ll_share_qq_kongjian;
    private LinearLayout ll_share_weixin;
    private LinearLayout ll_share_pengyou_quan;
    private LinearLayout ll_cancel;
    private LinearLayout ll_cancel_pop;
    int qd = 0;//0  未签到    1签到

    public static MineFragment instantiation() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fview = inflater.inflate(R.layout.mine_fragment_layout, null);
        ButterKnife.bind(this, fview);
        checkStoragePermission();
        init();
        return fview;
    }

    public void init() {
        ivQiandao.setImageResource(R.drawable.self_qd);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(PreferencesUtils.getString(getActivity(), "url"))) {
            ImgDataUtil.loadYuanImage(getActivity(), HttpIP.Base_IpIMage + PreferencesUtils.getString(getActivity(), "url"), ivTouxiang);
        }
        tvNicehng.setText(PreferencesUtils.getString(getActivity(), "user_name"));
        getPerData();
    }


    @OnClick({R.id.iv_qiandao, R.id.ll_personal_date, R.id.ll_goumai_fuwu, R.id.ll_xiaofei_jilu, R.id.ll_my_erweima, R.id.ll_tuijian_share, R.id.ll_set, R.id.ll_my_collection, R.id.ll_yijian_fankui, R.id.ll_my_service})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_qiandao:
                if (qd == 0) {
                    getData();
                } else {
                    CommonUtil.showToask(getActivity(), "您已签到！");
                }
                break;
            case R.id.ll_personal_date://个人资料
                intent = new Intent(getActivity(), PersonalDataActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_goumai_fuwu://购买服务
                intent = new Intent(getActivity(), PayServiceActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_xiaofei_jilu://消费记录
                intent = new Intent(getActivity(), XiaoFeiJiLuActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_my_erweima://二维码
                intent = new Intent(getActivity(), MyErWeiMaActivity.class);
                intent.putExtra("per", "1");
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_tuijian_share://分享
                new ShareAction(getActivity())
                        .withTitle("欢迎使用未医")
//                        .withText("未医分享内容")
                        .withTargetUrl(HttpIP.Base_IpXX + "share.rm?type=android")
                        .withMedia(new UMImage(getActivity(), R.drawable.logo))
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(umShareListener)
                        .open();
                break;
            case R.id.ll_set:
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_my_collection://我的收藏
                intent = new Intent(getActivity(), MineCollectionActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_yijian_fankui:
                intent = new Intent(getActivity(), YiJianFanKuiActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
            case R.id.ll_my_service://我的服务
                intent = new Intent(getActivity(), MyServiceActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.next_in, R.anim.next_out);
                break;
        }
    }

    private void ShowPopShare() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(getActivity());
        View v = inflater.inflate(R.layout.share_pop_layout, null);
        ll_share_qq = (LinearLayout) v.findViewById(R.id.ll_share_qq);
        ll_share_qq_kongjian = (LinearLayout) v.findViewById(R.id.ll_share_qq_kongjian);
        ll_share_weixin = (LinearLayout) v.findViewById(R.id.ll_share_weixin);
        ll_share_pengyou_quan = (LinearLayout) v.findViewById(R.id.ll_share_pengyou_quan);
        ll_cancel = (LinearLayout) v.findViewById(R.id.ll_cancel);
        ll_cancel_pop = (LinearLayout) v.findViewById(R.id.ll_cancel_pop);
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(v, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
        pop.showAtLocation(tvView, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        ll_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //TODO  请求成功之后设置
                pop.dismiss();
            }
        });

        ll_share_qq.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
        ll_cancel_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
    }

    /**
     * 关于分享
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);//10103   0   null

    }

    private UMShareListener umShareListener = new UMShareListener() {
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
            Toast.makeText(getActivity(), " onStart", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getActivity(), " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getActivity(), " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 签到
     */
    private void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.QD, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(getActivity(), "uid"));
        CallServer.getRequestInstance().add(getActivity(), 0, mRequest,
                new CustomHttpListener(getActivity(), true, QianDaoM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        QianDaoM model = ((QianDaoM) data);
                        PreferencesUtils.putString(getActivity(), "IsQD", "true");
                        ivQiandao.setImageResource(R.drawable.self_qd_pre);
                        qd = 1;
                        getPerData();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, true);
    }

    /**
     * 是否签到   和积分
     */
    private void getPerData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.PerMess, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(getActivity(), "uid"));
        CallServer.getRequestInstance().add(getActivity(), 0, mRequest,
                new CustomHttpListener(getActivity(), true, PerMessM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        PerMessM model = ((PerMessM) data);
                        PreferencesUtils.putString(getActivity(), "IsQD", model.getObject().getIsSign());
                       if(!TextUtils.isEmpty(model.getObject().getPoints())){
                           tvPerJf.setText(model.getObject().getPoints() + "分");
                       }else {
                           tvPerJf.setText("0分");
                       }

                        if (("false").equals(PreferencesUtils.getString(getActivity(), "IsQD"))) {
                            ivQiandao.setImageResource(R.drawable.self_qd);
                            qd = 0;
                        } else {
                            ivQiandao.setImageResource(R.drawable.self_qd_pre);
                            qd = 1;
                        }

                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, false);
    }
    //关于系统6.0以上的权限适配（此处分享用到）注意Manifest的导包

    private void checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                // 是否需要弹出一个解释申请该权限的提示给用户，如果为true，则可以弹。
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    Toast.makeText(getActivity(), "没权限", Toast.LENGTH_SHORT).show();
                    ActivityCompat.requestPermissions(
                            getActivity(),
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            0);
                } else {

                    // 在Fragment中申请权限，不要使用ActivityCompat.requestPermissions,
                    // 直接使用Fragment的requestPermissions方法，否则会回调到Activity的 onRequestPermissionsResult
                    ActivityCompat.requestPermissions(
                            getActivity(),
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            0);

                    // Const.LOCATION_REQUEST is an app-defined int constant.
                    // The callback method gets the result of the request.
                }

            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    Toast.makeText(getActivity(), "请求权限被拒绝，请重新开启权限", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
